
//preloading.....
load("library/common.js");

JEuler.system.loadJS("library/math.js");

(function() {

    function int2ascii(num) {
        num = parseInt(num, 10);
        return String.fromCharCode(num);
    };
    
    function ascii2int(str) {
        return String.charCodeAt(str);
    };
    
    function isAlpha(num) {
        var A = ascii2int("A"), Z = ascii2int("Z");
        var a = ascii2int("a"), z = ascii2int("z");
        return ((num>=a && num<=z) || (num>=A && num<=Z))
    }
    
    function XOR(a, b) {
        a = parseInt(a, 10);
        b = parseInt(b, 10);
        return a ^ b;
    }
    
    JEuler.system.loadJS("data/p59.dat");
    
    var ciperStr = p59data;
    
    //JEuler.system.out(ciperStr);
    
    JEuler.system.printCaption(59);
    var a = ascii2int("a"), z = ascii2int("z");
    
    var testWords = ["an", "and", "I", "this", "the"];
    
    var testStr = [], findKey;
    for(var i=0; i<=100; i++) {
        testStr[i] = ciperStr[i];
    }

    JEuler.system.startTimerCount();
    
    for(var i=a; i<=z; i++) {
        for(var j=a; j<=z; j++) {
            for(var k=a; k<=z; k++) {
                var key = [i, j, k]; 
                var index=-1;
                var count=0;
                var sentences = testStr.map(function(num){
                    index = (index+1)%3;
                    var temp = int2ascii(XOR(num, key[index]));    
                    if(temp == " ") count++;
                    return temp;
                }).join("");
                //JEuler.system.print(sentences.join("") + "\n");
                if(count>5 && sentences.indexOf("the")>-1 && sentences.indexOf("of")>-1) {
                    JEuler.system.print(sentences + "\n");
                    JEuler.system.print("Find..." + key + "\n");
                    findKey = key;
                    i=z, j=z, k=z;
                    break;
                }
            }
        }
    }
    
    //findKey = [103,111,100];
    index=-1;
    var sentences = ciperStr.map(function(num){
        index = (index+1)%3;
        var temp = int2ascii(XOR(num, findKey[index]));    
        return temp;
    }).join("");   

    JEuler.system.print("Original text:"); 
    JEuler.system.print(sentences); 

    index=-1;
    var sum = eval(ciperStr.map(function(num){
        index = (index+1)%3;
        var temp = XOR(num, findKey[index])
        return temp;
    }).join("+"));   
    
    JEuler.system.print("Sum=" + sum + "\n"); 
    
    JEuler.system.printTimerCount();

    
    
})();
